//
//  EmailExtensionIOS.m
//  EmailExtensionIOS
//
//  Based on the example by Piotr Kościerzyński, http://flashsimulations.com/2011/11/30/ios-native-extension-for-adobe-air-in-app-mail-composer/

#import "MailComposerDelegate.h"
#import "EmailExtensionIOS.h"


@implementation EmailExtensionIOS


typedef enum ARGS 
{
    ARG_SUBJECT = 0,
    ARG_BODY = 1,
    ARG_TO = 2,
    ARG_CC = 3,
    ARG_BCC = 4,
    ARG_ATTACHMENTS = 5,
    ARG_USE_HTML = 6,

    ARG_COUNT_MAX

} ARG_INDEX;


MailComposerDelegate * mailComposerDelegate = NULL;


NSString * getNSStringFromCString( FREObject arg )
{
    NSString * resultString = NULL;
    
    uint32_t strLength = 0;
    const uint8_t * argCString = NULL;
    FREResult argumentResult = FREGetObjectAsUTF8( arg, &strLength, &argCString );
    
    if ( ( FRE_OK == argumentResult ) && ( 0 < strLength ) && ( NULL != argCString ) )
    {
        resultString = [ NSString stringWithUTF8String:(const char *) argCString ];
    }
    
    return resultString;
}


int isEmailAvailable ( void )
{
    int isAvailable = 0;
    
    Class mailInterface = ( NSClassFromString( @"MFMailComposeViewController" ) );
	
    if ( NULL != mailInterface ) 
    {
        // MFMailComposeViewController exists, now check whether the user has configured their e-mail:
		if ( [ mailInterface canSendMail ] ) 
        {
            isAvailable = 1; // E-mail has been configured
		}
	}
    
    return isAvailable;
}


FREObject ActionScriptIsEmailConfigured(FREContext ctx, void* funcData, uint32_t argc, FREObject argv[])
{
    BOOL isAvailable = isEmailAvailable();
    
    FREObject result;
    FRENewObjectFromBool( isAvailable, &result );
    
    return result;
}


FREObject ActionScriptSendEmail( FREContext ctx, void * funcData, uint32_t argc, FREObject argv[] )
{
    if ( !isEmailAvailable() )
    {
        return NULL;
    }
    
    // Extract the e-mail parameters:
    NSString * subject          = ( ARG_SUBJECT < argc )   ? getNSStringFromCString( argv[ ARG_SUBJECT ] )     : NULL;
    NSString * body             = ( ARG_BODY < argc )      ? getNSStringFromCString( argv[ ARG_BODY ] )        : NULL;
    NSString * recipientToList  = ( ARG_TO < argc )        ? getNSStringFromCString( argv[ ARG_TO ] )          : NULL;
    NSString * recipientCcList  = ( ARG_CC < argc )        ? getNSStringFromCString( argv[ ARG_CC ] )          : NULL;
    NSString * recipientBccList = ( ARG_BCC < argc )       ? getNSStringFromCString( argv[ ARG_BCC ] )         : NULL;
    
    uint32_t useHtmlValue = 1;
    if ( ARG_USE_HTML < argc )
    {
        FREGetObjectAsBool( argv[ ARG_USE_HTML ], &useHtmlValue );
    }
    Boolean useHtml = useHtmlValue;
    
    // And check for attachments:
    uint32_t attachmentsArrayLength = 0;
    if ( (argc >= ARG_COUNT_MAX) && (FRE_OK != FREGetArrayLength(argv[ARG_ATTACHMENTS], &attachmentsArrayLength))) 
    {
        FREDispatchStatusEventAsync( ctx, (uint8_t*)[ @"MAIL_COMPOSER_EVENT" UTF8String ], (uint8_t*)[@"No attachments found..." UTF8String] );
    }
    
    NSMutableString * attachmentsString = NULL;
    if ( 1 <= attachmentsArrayLength )
    {
        static NSString * ATTACHMENTS_SEPARATOR = @"----";
        
        attachmentsString = [ [ NSMutableString alloc ] init ];
        
        uint32_t attachmentEntryLength = 0;
        const uint8_t *attachmentEntryCString = NULL;
        
        for (int i = 0; i < attachmentsArrayLength; i++) 
        {
            FREObject arrayElement = NULL;
            FREGetArrayElementAt( argv[ARG_ATTACHMENTS], i, &arrayElement );
            FREGetObjectAsUTF8( arrayElement, &attachmentEntryLength, &attachmentEntryCString );
            
            [ attachmentsString appendString:[ NSString stringWithUTF8String: ( char * )attachmentEntryCString ] ];
            
            if ( ( attachmentsArrayLength - 1 ) > i )
            {
                [ attachmentsString appendString : ATTACHMENTS_SEPARATOR ];
            }
        }
    }
    
    if ( NULL == mailComposerDelegate )
    {
        mailComposerDelegate = [ [ MailComposerDelegate alloc ] init ];
    }
    
    [ mailComposerDelegate setContext : ctx ];
    
    [ mailComposerDelegate sendEmail : subject 
                        toRecipients : recipientToList 
                        ccRecipients : recipientCcList
                       bccRecipients : recipientBccList 
                         messageBody : body 
                             useHtml : useHtml
                     attachmentsData : attachmentsString ];
    
    if ( NULL != attachmentsString )
    {
        [ attachmentsString release ];
    }
    
    return NULL;
}


void EmailExtensionContextInitializer(
                                      void * extData,
                                      const uint8_t* ctxType,
                                      FREContext ctx,
                                      uint32_t* numFunctionsToSet,
                                      const FRENamedFunction** functionsToSet)
{
    static FRENamedFunction extensionFunctions[] =
    {
        { (const uint8_t*) "as_sendEmail", NULL, &ActionScriptSendEmail },
        { (const uint8_t*) "as_isEmailConfigured", NULL, &ActionScriptIsEmailConfigured }
    };
    
    *numFunctionsToSet = sizeof( extensionFunctions ) / sizeof( FRENamedFunction );
    *functionsToSet = extensionFunctions;
}


void EmailExtensionContextFinalizer(FREContext ctx) 
{
    return;
}


void EmailExtensionInitializer(void** extDataToSet, 
                    FREContextInitializer* ctxInitializerToSet, 
                    FREContextFinalizer* ctxFinalizerToSet) 
{
    
    *extDataToSet = NULL;
    *ctxInitializerToSet = &EmailExtensionContextInitializer;
    *ctxFinalizerToSet = &EmailExtensionContextFinalizer;
}


void EmailExtensionFinalizer(void* extData) 
{    
    return;
}

@end
